package com.gcloud.mesh.dcs.task;

import com.gcloud.mesh.dcs.dao.AliPowerDao;
import com.gcloud.mesh.dcs.entity.AliPowerEntity;
import com.gcloud.mesh.dcs.enums.AliPowerEventRepType;
import com.gcloud.mesh.header.vo.supplier.AliPower.AliPowerEventRepVo;
import com.gcloud.mesh.supplier.adapter.AliPowerConsumptionAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class AliPowerEventsTask {
    private final AliPowerConsumptionAdapter adapter;
    private final AliPowerDao aliPowerDao;

    @Autowired
    public AliPowerEventsTask(AliPowerConsumptionAdapter adapter, AliPowerDao aliPowerDao) {
        this.adapter = adapter;
        this.aliPowerDao = aliPowerDao;
    }

    /**
     * 检查设备释放是否成功
     */
    @Scheduled(fixedDelay = 1000)
    public void work() {
        log.debug("[AliPowerEventsTask]开始检查设备在功耗平台的情况");
        List<AliPowerEventRepVo> list = adapter.events();
        if (!list.isEmpty()) {
            for (AliPowerEventRepVo response:list){
                AliPowerEntity aliPowerEntity = aliPowerDao.findOneByProperty("esn", response.getValue());
                if (aliPowerEntity != null && Objects.equals(response.getType(), AliPowerEventRepType.ME_DEVICE_RELEASE.name())) {
                    log.info("[AliPowerEventsTask]设备{}已被释放", response.getValue());
                }
            }
        }
        log.debug("[AliPowerEventsTask]结束检查设备在功耗平台的情况");
    }
}
